<template>
    <div class="dashboard-container">
        <!-- 筛选查询 -->
        <el-form :inline="true">
            <el-form-item label="任务名">
                <el-input placeholder="请输入任务名" v-model="params.name" clearable></el-input>
            </el-form-item>
            <el-button type="primary" @click="getList">查询</el-button>
            <el-button @click="handleAdd('create')">新增</el-button>
            <el-button @click="handleMultipleDelete" :disabled="multipleSelection.length==0" >批量删除</el-button>
        </el-form>

        <!-- 数据列表 -->
        <el-table :data="list" v-loading="loading" @selection-change="handleSelectionChange">
            <el-table-column
                type="selection"
                width="55"
            >
            </el-table-column>
            <el-table-column label="序号" type="index"></el-table-column>
            <el-table-column label="任务名" prop="name"></el-table-column>
            
            <el-table-column label="导入数量" prop="totalPersonCount"></el-table-column>
            <el-table-column label="已领取" prop="takenPersonCount"></el-table-column>
            <el-table-column label="最大认领数" prop="maxCountPerUser"></el-table-column>
            <el-table-column label="任务创建时间" prop="createTime"></el-table-column>
            <el-table-column label="分配用户" >
                <template slot-scope="{row}">
                    {{ row.assignType==1 ? "指定用户": "所有用户" }}
                </template>
            </el-table-column>
            <el-table-column label="完成情况">
                <template slot-scope="{row}">
                    <el-button type="text" @click="handleLook(row.id)">查看</el-button>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template slot-scope="{row}">
                    <el-button type="text" @click="handleAdd('update', row)">编辑</el-button>
                    <el-button type="text" @click="handleDelete(row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div style="padding-top:30px; text-align: right;">
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="params.pageIndex+1"
                background
                :page-sizes="[10, 20, 30, 40]"
                :page-size="params.pageCount"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </div>

        <!-- 新增 -->
        <el-dialog :title="dialogType=='create'?'新增任务':'编辑任务'" :visible.sync="dialogVisible" width="800px">
            <el-form label-width="100px" :model="temp"  :rules="rules" ref="ruleForm">
                <el-form-item label="分配方式" prop="type" v-if="dialogType=='create'">
                    <el-radio v-model="temp.type" :label="1">号码导入</el-radio>
                    <el-radio v-model="temp.type" :label="2">号码输入(可复制粘贴)</el-radio>
                </el-form-item>
                <el-form-item label="手机号码输入" prop="phone" v-if="temp.type==2&&dialogType=='create'">
                    <el-input type="textarea" v-model="temp.phone" :rows="2" placeholder="请输入多个手机号码以英文,分隔"></el-input>
                </el-form-item>
                <el-form-item label="任务名" prop="name">
                    <el-input v-model="temp.name" placeholder="请输入任务名"></el-input>
                </el-form-item>
                <el-form-item label="指定用户" v-if="dialogType=='create'">
                    <el-select 
                        v-model="temp.assignUserIds" 
                        placeholder="请选择用户，不选择则为全部用户可领取" 
                        multiple 
                        clearable 
                        style="width: 100%"
                        filterable
                    >
                        <el-option :label="item.label" :value="item.value" :key="item.value" v-for="item in UserList"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="最大认领数" prop="maxCountPerUser" v-if="dialogType=='create'">
                    <el-input-number v-model="temp.maxCountPerUser " placeholder="请输入最大认领数"></el-input-number>
                </el-form-item>
                <el-form-item label="任务列表" v-if="temp.type==1&&dialogType=='create'" prop="phoneFileName">
                    <el-upload
                        class="upload-demo"
                        ref="upload"
                        :action="BASE_URL+'/common/uploadLocalFile'"
                        :on-remove="handleRemove"
                        :on-success="handleSuccess"
                        :file-list="fileList"
                    >
                        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                        <div slot="tip" class="el-upload__tip">
                            只能上传excel文件，且不超过500kb
                            <a 
                                href="https://unicall.oss-cn-shanghai.aliyuncs.com/case/%E6%89%B9%E9%87%8F%E5%AF%BC%E5%85%A5%E5%8F%B7%E7%A0%81.xlsx"
                                style="color: #409EFF;margin-left: 20px;"
                            >下载模板</a>
                        </div>
                    </el-upload>
                </el-form-item>
            </el-form>
            <div style="text-align: right;">
                <el-button @click="dialogVisible=false">取消</el-button>
                <el-button type="primary" @click="submitForm('ruleForm')">确认</el-button>
            </div>
        </el-dialog>

        <!-- 任务完成情况 -->
        <el-dialog title="任务完成情况" :visible.sync="dialogVisibleDetail" width="800ox">
            <el-table :data="detailList">
                <el-table-column type="index" label="序号"></el-table-column>
                <el-table-column prop="user.nickName" label="员工"></el-table-column>
                <el-table-column prop="takenCount" label="应拨打数"></el-table-column>
                <el-table-column prop="callCount" label="已拨打数"></el-table-column>
            </el-table>
        </el-dialog>

    </div>
  </template>
  
  <script>
  import { mapGetters } from 'vuex'
  import { collectionGetlist, collectionDelete, collectionCreateTask, collectionUpdate, collectionGetPersonList, collectionGetUserList } from '@/api/collection'
  import { BASE_URL } from '@/utils/common'
  import { userGetlist } from '@/api/user'
  import moment from 'moment'
   
  export default {
    name: 'Dashboard',
    computed: {
      ...mapGetters([
        'name'
      ])
    },
    data(){
      return {
        BASE_URL,
        list: [],
        info: {},
        params: {
            pageCount: 10,
            pageIndex: 0,
            name: '',
            types: [1]
        },
        total: 0,
        dialogVisible: false,
        temp:{},
        rules: {
            name: [{ required: true, message: '请输入任务名', trigger: 'blur' }],
            phoneFileName: [{ required: true, message: '请上传任务文件', trigger: 'blur' }],
            maxCountPerUser: [{ required: true, message: '请输入最大认领数', trigger: 'blur' }],
        },
        loading: false,
        multipleSelection: [],
        fileList: [],
        file: {},
        UserList: [],
        dialogType: 'create',
        dialogVisibleDetail: false,
        detailList: []
      }
    },
    mounted(){
        this.info = JSON.parse(localStorage.getItem('info'))
        this.getList();
    },
    methods: {
        //点击查看任务完成情况
        async handleLook(id){
            let data = await collectionGetUserList({ dataId: id, pageCount: 10 })
            this.detailList = data.data.list
            this.dialogVisibleDetail = true;
        },
        //获取用户列表
        async getUserList(){
            let data = await userGetlist({ pageCount: 999 });
            this.UserList = data.data.list.map(item=>{
                return { label: item.nickName+'|'+item.phone, value: item.id }
            })
        },
        handleSuccess(response, file, fileList){
            this.temp.phoneFileName = response.data
        },
        handleRemove(file, fileList){
            this.temp.phoneFileName = ''
        },
        //批量删除提交
        handleMultipleDelete(){
            this.$confirm('此操作将永久删除任务, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                let dataIds = this.multipleSelection.map(item=>item.id)
                await collectionDelete({ dataIds })
                this.getList();
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });          
            });
        },
        //点击多选
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        //点击新增
        handleAdd(type, row){
            this.dialogType = type;
            if(type=='create'){
                this.getUserList();
                this.temp = {
                    type: 1,
                    phone: '',
                    name: '',
                    maxCountPerUser: '',
                    hostId: this.info.id,
                    phoneFileName: '',
                    persons: [],
                    maxCountPerUser: '',
                    assignUserIds: []
                };
            }else{
                this.temp = {
                    dataId: row.id,
                    name: row.name
                }
            }
            
            this.dialogVisible = true;
        },
        //提交表单
        submitForm(formName){
            
            this.$refs[formName].validate(async (valid) => {
                
                if (valid) {
                    if(this.dialogType=='create'){
                        let createTemp = {
                            hostId: this.temp.hostId,
                            maxCountPerUser: this.temp.maxCountPerUser,
                            name: this.temp.name,
                            persons: this.temp.phone.split(',').map(item=>{ return { phone: item, realName: '' } }),
                            phoneFileName: this.temp.phoneFileName,
                            assignUserIds: this.temp.assignUserIds
                        }
                        let { data } = await collectionCreateTask(createTemp)
                        this.$message({
                            type: 'success',
                            message: `导入成功${data.successCount}, 风险号码${data.duplicatedCount}, 错误号码${data.errorCount}`
                        });
                    }else{
                        await collectionUpdate(this.temp);
                        this.$message({
                            type: 'success',
                            message: '编辑成功'
                        })
                    }
                    
                    this.dialogVisible = false;
                    this.getList();
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        //点击删除
        handleDelete(id){
            this.$confirm('此操作将永久删除该任务, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                await collectionDelete({ dataIds: [id] })
                this.getList();
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });          
            });
        },
        //获取数据列表
        async getList(){
            this.loading = true;
            let data = await collectionGetlist(this.params)
            this.loading = false;
            this.list = data.data.list.map(item=>{
                item.createTime = moment(item.createTime).format('YYYY-MM-DD HH:mm:ss')
                return item;
            })
            this.total = data.data.totalCount;
        },
        //切换数量
        handleSizeChange(val){
            this.params.pageIndex = 0;
            this.params.pageCount = val;
            this.getList();
        },
        //切换页码
        handleCurrentChange(val){
            this.params.pageIndex = val-1;
            this.getList();
        }
    }
  }
  </script>
  
  <style lang="scss" scoped>
  .dashboard {
    &-container {
      margin: 30px;
      
    }
    &-text {
      font-size: 30px;
      line-height: 46px;
    }
  }
  </style>
  